﻿var app = require('express').createServer(), io = require('socket.io').listen(app);
var nicknames = {};
var usercount = 0;
app.listen(8081);

io.sockets.on('connection', function (socket) {
  socket.on('user message', function (msg) {
    socket.broadcast.emit('user message', socket.nickname, msg);
  });

  socket.on('userinput', function (msg) {
    socket.broadcast.emit('userinput', socket.nickname, msg);
  });

  socket.on('nickname', function (nick, fn) {
    if (nicknames[nick]) {
      fn(true);
    } else {

      fn(false);
      nicknames[nick] = socket.nickname = nick;      
      usercount++;
      var index = 0;
      for (var i in nicknames) {
        index++;
        if (nicknames[i] == nick) break;
      }
      socket.broadcast.emit('announcement', nick + ' connected');
      io.sockets.emit('nicknames', nicknames);
      socket.emit('userinfo', index);
    }
  });

  socket.on('disconnect', function () {
    if (!socket.nickname) return;

    delete nicknames[socket.nickname];
    usercount--;
    socket.broadcast.emit('announcement', socket.nickname + ' disconnected');
    socket.broadcast.emit('nicknames', nicknames);
  });

  //socket.emit('news', { hello: 'world' });
  //socket.on('my other event', function (data) {
  //console.log(data);
  //});
});